package edu.zqu.file.project.controller;

import edu.zqu.common.result.ZQUResult;
import edu.zqu.file.project.service.UploadService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * @Author 吴典秋
 * @Date 2020/5/19 13:02
 * @Description:
 * @Version 1.0
 */
@Controller
public class FileController {
    @Autowired
    private UploadService uploadService;

    @GetMapping("/test")
    public String test(){
        return "测试成功";
    }

    @PostMapping("/upload")
    @ResponseBody
    public ZQUResult uploadImage(@RequestParam("file") MultipartFile file) {
        String url = uploadService.uploadImage(file);
        return ZQUResult.success(url);
    }

    /**
     * 文件下载
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/download", method = {RequestMethod.GET})
    public void  download(HttpServletResponse response, HttpServletRequest request) throws Exception{
        String fileUrl = request.getParameter("fileUrl");
        byte[] data = uploadService.download(fileUrl);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("lombok一些特性.jpg", "UTF-8"));
        // 写出
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.write(data, outputStream);
    }
}
